<?php

namespace app\supplyer\controller\api;

use app\ApiController;
use app\supplyer\model\SupplyerCategoryModel;
use app\supplyer\model\SupplyerModel;

class Supplier extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new SupplyerModel();
    }

    public function info()
    {
        $cateModel = new SupplyerCategoryModel();
        $supplier = $this->Model->where(['uid' => $this->userInfo['user_id']])->find();
        if(!$supplier){
            $supplier['is_audit'] = -1;
            $supplier['images'] = [];
        }else{
            if($supplier['images']){
                $supplier['images'] = explode(',',$supplier['images']);
            }else{
                $supplier['images'] = [];
            }
        }

        $cate_list = $cateModel->field('id as value,name as label')->where(['status' => 1,'pid' => 0])->select()->toArray();
        foreach ($cate_list as &$val){
            $val['children'] = $cateModel->field('id as value,name as label')->where(['status' => 1,'pid' => $val['value']])->select();
        }
        return $this->success(compact('supplier','cate_list'));
    }

    public function apply()
    {
        $data = [
            'company_name' => input('company_name',''),
            'consignee' => input('consignee',''),
            'moblie' => input('moblie',''),
            'cid' => input('cid',0),
            'images' => input('images',''),
        ];
        $data['supplyer_name'] = $data['moblie'];
        $data['password'] = _hash('Aa123456');
        $data['uid'] = $this->userInfo['user_id'];
        $data['is_audit'] = 0;

        $supplier = $this->Model->where(['uid' => $this->userInfo['user_id']])->find();
        if($supplier){
//            return $this->error('您已经申请过了');
            $this->Model->where(['uid' => $this->userInfo['user_id']])->update($data);
        }else{
            $data['add_time'] = time();
            $this->Model->insert($data);
        }

        return $this->success('申请成功，等待审核');
    }
}
